<template>
  <div>
    <Modal v-model="cropShow" width="70" :styles="{top: '20px'}" :mask-closable="false">
      <p slot="header" style="color:#409EFF;text-align:center">
        <Icon type="scissors"></Icon>
        <span>图片剪切</span>
      </p>
      <div style="height: 500px; width: 70%;">
        <vueCropper
          ref="cropper"
          :img="imgSrc"
          :outputSize="1"
          :full="false"
          outputType="jpeg"
          :info="false"
          :canMove="true"
          :canMoveBox="true"
          :autoCrop="true"
          :fixed="true"
          :fixedNumber="fixedNumber"
          @realTime="timeImg">
        </vueCropper>
      </div>
      <div class="timeImg">
        <p style="font-size: 16px;margin-bottom: 10px;">效果图预览</p>
        <img :src="imgTime" alt="" height="100" v-show="imgTime !== ''" style="border: 1px solid #dddee1;">
      </div>
      <div slot="footer">
        <Button type="success" @click="cropImg" icon="checkmark-round">就这样</Button>
        <Button type="error" @click="reset">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import vueCropper from 'vue-cropper'
export default {
  name: 'image-util',
  data () {
    return {
      imgSrc: '',
      imgTime: '',
      cropShow: false,
      name: ''
    }
  },
  methods: {
    timeImg (e) {
      this.$refs.cropper.getCropData((data) => {
        this.imgTime = data
      })
    },
    setImage (e) {
      this.cropShow = true
      let file = e.e
      this.name = e.name
      if (!file.type.includes('image/')) {
        this.$Message.error('请选择图片文件')
        return
      }
      if (typeof FileReader === 'function') {
        const reader = new FileReader()
        reader.onload = (event) => {
          this.imgSrc = event.target.result
        }
        reader.readAsDataURL(file)
      } else {
        this.$Message.error('没有FileReader')
      }
    },
    cropImg () {
      this.cropShow = false
      this.$refs.cropper.getCropBlob((blob) => {
        let data = {
          imgTime: this.imgTime,
          blob,
          name: this.name
        }
        this.$emit('cropImg', data)
      })
    },
    reset () {
      this.cropShow = false
    }
  },
  props: ['fixedNumber'],
  components: {
    vueCropper
  },
  created () {}
}
</script>

<style scoped>
  .timeImg{
    position: absolute;
    margin-right: 10px;
    padding: 10px;
    right: 0;
    top: 66px;
    width: 28%;
    height: 500px;
    border: 1px solid #dddee1;
    border-radius: 3px;
  }
</style>
